// pages/handle/index.js
const storageService = require('../../../services/storage')
import {
  Toast
} from 'tdesign-miniprogram';

function isNumber(value) {
  if (value == null || value == undefined || value.length == 0) {
    return false;
  }
  return !isNaN(value);
}

function isEmpty(value) {
  return (value == null || value == undefined || value.length == 0);
}

function isEmptyObj(obj) {
  return (obj == null || obj == undefined || Object.keys(obj).length === 0);
}

// 获取 App 实例
const appInstance = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    did: null,
    curTab: 'handle',
    tabs: [{
        value: 'device',
        label: '自动',
        icon: '/images/icons/auto_0.png'
      },
      {
        value: 'handle',
        label: '手动',
        icon: '/images/icons/handle_1.png'
      },
      {
        value: 'set',
        label: '设置',
        icon: '/images/icons/set_0.png'
      },
    ],
    handCfg: {},
    deviceCfg: {},

    autoRun: 0,
    longtap: false,
    showWithInput: false,
    modeName: "",
    showWithHandSetting: false,
    timeoutObj: null,
    verObj: {
      "t": "",
      "v": 0,
      "s": ""
    },
    isHandVer: false,
    hasTempSync: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    this.data.did = options.did;
    let autoRunCfg =  storageService.getAutoRunCfg(this.data.did)
    this.setData({
      autoRun: isEmptyObj(autoRunCfg) ? 0 : autoRunCfg.sRun
    });
    let dobj = storageService.getDeviceInfo(options.did)
    this.data.deviceCfg = dobj;

    let tvobj = appInstance.deviceVerMap[this.data.did];
    if (!isEmptyObj(tvobj)) {
      this.verObj = JSON.parse(JSON.stringify(tvobj));
      this.setData({
        isHandVer: (this.verObj.t == "C")
      });
    }
    let tempSync = storageService.getTmpSynced(options.did)
    this.hasTempSync = !isEmpty(tempSync);
    this.getAndInitChs();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const $t = this;
    wx.$event.on(this.data.deviceCfg.topicSub, this, (obj) => {
      if (obj.type == "status") {
        if ($t.data.autoRun != obj.msg.sRun) {
          $t.setData({
            autoRun: obj.msg.sRun
          });
        }
      } else if (obj.type == "syncHandUp") {
        $t.confirmPopSyncToDeviceDialogResult(1);
      }
    });
  },
  onGoHome() {
    wx.redirectTo({
      url: "/pages/index/index",
    });
  },
  onTabChange(e) {
    let v = e.detail.value;
    if ("handle" == v) {
      return;
    }
    let url = "/packageB/pages/" + v + "/index?did=" + this.data.did;
    wx.redirectTo({
      url: url
    });
  },
  getAndInitChs() {
    let handCfg = storageService.getHandCfg(this.data.did)
    if (isEmptyObj(handCfg)) {
      let chCfg = storageService.getDeviceChannels(this.data.did)
      handCfg = {
        sel: 0,
        handM: 30,
        modes: [{
            "nm": this.data.isHandVer ? "手动模式" : "模式一",
            "cls": []
          },
          {
            "nm": this.data.isHandVer ? "临时开灯" : "模式二",
            "cls": []
          }
        ]
      };
      for (var j = 0; j < handCfg.modes.length; j++) {
        let cls = handCfg.modes[j].cls;
        for (var i = 0; i < chCfg.length; i++) {
          if (chCfg[i].u == 0) {
            continue;
          }
          cls.push({
            "n": chCfg[i].n,
            "nm": chCfg[i].nm,
            "c": chCfg[i].c,
            "v": 0
          });
        }
      }
      storageService.saveHandCfg(this.data.did, handCfg)
    }
    if (this.data.isHandVer && handCfg.modes[0].nm != "手动模式") { //兼容老版本
      handCfg.modes[0].nm = "手动模式";
      handCfg.modes[1].nm = "临时开灯";
      handCfg.handM = 30;
      storageService.saveHandCfg(this.data.did, handCfg)
    }
    this.setData({
      handCfg: JSON.parse(JSON.stringify(handCfg))
    });
    console.log(this.data.handCfg);
  },
  sliderChange(e) {
    if (this.valChange(e)) {
      storageService.saveHandCfg(this.data.did, this.data.handCfg)
      this.sendValChgMsg(e);
    }
  },
  sliderChangeing(e) {
    this.valChange(e);
  },
  steppperChange(e) {
    if (this.valChange(e)) {
      storageService.saveHandCfg(this.data.did, this.data.handCfg)
      this.sendValChgMsg(e);
    }
  },
  valChange(e) {
    if (this.data.isHandVer) {
      if (this.data.autoRun == 1 && this.data.handCfg.sel == 0) {
        this.showToast("自动模式下无法手动调整!");
        return false;
      }
    } else {
      if (this.data.autoRun == 1) {
        this.showToast("自动模式下无法手动调整!");
        return false;
      }
    }

    if (this.data.handCfg.sel < 0) {
      this.showToast("请先选择模式!");
      return false;
    }
    const {
      value
    } = e.detail;
    let idx = e.currentTarget.dataset.idx;
    let str = "handCfg.modes[" + this.data.handCfg.sel + "].cls[" + idx + "].v";
    this.setData({
      [str]: value
    });
    return true;
  },
  sendValChgMsg(e) {
    if (this.data.isHandVer && this.data.handCfg.sel == 1) {
      return;
    }
    const {
      value
    } = e.detail;
    let idx = e.currentTarget.dataset.idx;
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgVal", {
      n: this.data.handCfg.modes[this.data.handCfg.sel].cls[idx].n,
      v: value
    });
  },
  selMode(e) {
    if (!this.data.isHandVer) {
      if (this.data.longtap) {
        this.data.longtap = false;
        return;
      }
    }

    let idx = e.currentTarget.dataset.idx;
    if (this.data.handCfg.sel == idx) {
      return;
    }
    this.setData({
      "handCfg.sel": idx
    });
    storageService.saveHandCfg(this.data.did, this.data.handCfg)
  },
  editModeName() {
    if (this.data.isHandVer) {
      return;
    }
    this.data.longtap = true;
    this.setData({
      showWithInput: true,
      modeName: this.data.handCfg.modes[this.data.handCfg.sel].nm
    });
  },
  editConfirm() {
    if (isEmpty(this.data.modeName)) {
      this.showToast("名称不能为空!");
      this.setData({
        modeName: this.data.handCfg.modes[this.data.handCfg.sel].nm
      });
      return;
    }
    let str = "handCfg.modes[" + this.data.handCfg.sel + "].nm";
    this.setData({
      [str]: this.data.modeName
    });
    storageService.saveHandCfg(this.data.did, this.data.handCfg)
    this.closeDialog();
  },
  closeDialog() {
    this.setData({
      showWithInput: false
    });
  },
  bindKeyInput: function (e) {
    let val = e.detail.value;
    if (isEmpty(val)) {
      val = "";
    }
    this.setData({
      modeName: val
    })
  },
  confirmPopSyncToDeviceDialogResult(succ) {
    const $t = this;
    wx.hideLoading();
    if (succ == 0) {
      $t.showToast("请求响应超时...");
    } else {
      $t.showToast("同步成功!");
      clearTimeout($t.data.timeoutObj);
      storageService.setTmpSynced(this.data.did)
      $t.hasTempSync = true;
    }
  },
  handOn() {
    if (!this.hasTempSync) {
      this.showToast("请先同步临时配置到设备...");
      return;
    }
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "handOn", null);
    this.showToast("命令已发送...");
  },
  handOff() {
    if (!this.hasTempSync) {
      this.showToast("请先同步临时配置到设备...");
      return;
    }
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "handOff", null);
    this.showToast("命令已发送...");
  },
  handCanel() {
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "handCanel", null);
    this.showToast("命令已发送...");
  },
  handSetting() {
    this.setData({
      showWithHandSetting: true,
      "handCfg.handM": this.data.handCfg.handM
    });

  },
  confirmHandDialog() {
    let cls = this.data.handCfg.modes[1].cls;
    let flag = true;
    for (var i = 0; i < cls.length; i++) {
      if (cls[i].v != 0) {
        flag = false;
        break;
      }
    }
    if (flag) {
      this.showToast("临时开灯灯光强度配置不能全为0!");
      return;
    }
    this.closeHandDialog();
    const $t = this;
    wx.showLoading({
      title: 'Loading......',
      mask: true,
      success: function () {
        let obj = {
          "handM": $t.data.handCfg.handM
        };
        let vArr = [];
        let cls = $t.data.handCfg.modes[1].cls;
        for (var i = 0; i < cls.length; i++) {
          vArr.push(cls[i].v);
        }
        obj.tl = vArr;
        console.log(obj);
        appInstance.sendMtMsg($t.data.deviceCfg.topicSend, "syncHandUp", obj);
        $t.data.timeoutObj = setTimeout(function () {
          $t.confirmPopSyncToDeviceDialogResult(0);
        }, 5000);
      }
    });
  },
  closeHandDialog() {
    this.setData({
      showWithHandSetting: false
    });
  },
  bindKeyHandMInput: function (e) {
    let val = e.detail.value;
    if (isEmpty(val)) {
      return;
    }
    if (!isNumber(val)) {
      val = 0;
    } else {
      val = parseInt(val);
    }
    if (val < 1 || val > 999) {
      this.setData({
        "handCfg.handM": this.data.handCfg.handM
      });
    } else {
      this.setData({
        "handCfg.handM": val
      });
      storageService.saveHandCfg(this.data.did, this.data.handCfg)
    }
  },
  handAllOn() {
    if (this.data.autoRun == 1) {
      return;
    }
    let vArr = [];
    let cls = this.data.handCfg.modes[this.data.handCfg.sel].cls;
    for (var i = 0; i < cls.length; i++) {
      vArr.push({
        "n": cls[i].n,
        "v": 100
      });
    }
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgValAll1", vArr);
    this.showToast("命令已发送...");
  },
  handAllConfig() {
    if (this.data.autoRun == 1) {
      return;
    }
    let vArr = [];
    let cls = this.data.handCfg.modes[this.data.handCfg.sel].cls;
    for (var i = 0; i < cls.length; i++) {
      vArr.push({
        "n": cls[i].n,
        "v": cls[i].v
      });
    }
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgValAll1", vArr);
    this.showToast("命令已发送...");
  },
  handAllOff() {
    if (this.data.autoRun == 1) {
      return;
    }
    appInstance.sendMtMsg(this.data.deviceCfg.topicSend, "chgValAll0", null);
    this.showToast("命令已发送...");
  },


  showToast(msg) {
    Toast({
      context: this,
      selector: '#t-toast',
      message: msg,
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.$event.remove(this.data.deviceCfg.topicSub, this);
  },
})